package com.search;

import com.alibaba.fastjson.JSON;
import com.hmall.common.clients.FeginClient;
import com.hmall.common.dto.Item;
import com.hmall.common.dto.ItemDoc;
import com.hmall.common.dto.PageDTO;
import org.apache.http.HttpHost;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.common.xcontent.XContentType;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.io.IOException;
import java.util.List;

/**
 * @author zx
 * @date 2021/11/8 9:24
 */
@SpringBootTest(classes = SearchApplication.class)
//@SpringBootTest
public class index {

    private RestHighLevelClient client;


//    @Autowired
//    ISearchService iSearchService;

    @Autowired
    private FeginClient feginClient;
    
    /**
     * 批量导入
     * @throws Exception
     */
    @Test
    void testBulkAddRequest() throws Exception{
        int page=1;
        int size=1000;

//        BulkResponse bulk = null;
        while (true) {
            PageDTO<Item> pageDTO=feginClient.list(page,size);
            List<Item> list = pageDTO.getList();
            page++;
            if (!(list.size()>0) ){
                break;
            }
            BulkRequest hmall = new BulkRequest("hmall");
            for (Item hmall1 : list) {
                ItemDoc itemDoc=new ItemDoc(hmall1);
                //创建文档添加请求
                IndexRequest request = new IndexRequest();
                // 将文档添加到请求中
                request.id(String.valueOf(itemDoc.getId()));
                request.source(JSON.toJSONString(itemDoc), XContentType.JSON);
                hmall.add(request);

            }
            //4.调用client执行bulk方法
            BulkResponse bulk = client.bulk(hmall, RequestOptions.DEFAULT);
            //解析响应

            System.out.println(bulk.status());

        }
    }






    @BeforeEach
    void setUp() {
        this.client = new RestHighLevelClient(RestClient.builder(
                HttpHost.create("http://192.168.200.130:9200")
        ));
    }

    @AfterEach
    void tearDown() throws IOException {
        this.client.close();
    }
}
